package com.atguigu.gmall.gateway.filter;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.atguigu.gmall.common.result.Result;
import com.atguigu.gmall.common.result.ResultCodeEnum;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.cloud.gateway.filter.GatewayFilterChain;
import org.springframework.cloud.gateway.filter.GlobalFilter;
import org.springframework.core.Ordered;
import org.springframework.core.io.buffer.DataBuffer;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.http.HttpCookie;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.http.server.reactive.ServerHttpRequest;
import org.springframework.http.server.reactive.ServerHttpResponse;
import org.springframework.stereotype.Component;
import org.springframework.util.AntPathMatcher;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono;

import java.util.List;

/**
 * @Author: 小兰
 * @Date: 2023/5/4 20:28
 */
@Component
public class AuthFilter implements GlobalFilter, Ordered {
    @Autowired
    private RedisTemplate redisTemplate;

    private AntPathMatcher antPathMatcher = new AntPathMatcher();

    /**
     * 需要登录才可以访问静态页面地址
     */
    @Value("${authUrls.url}")
    private List<String> authUrl;

    /**
     * 同意验证用户身份请求
     * @param exchange 交换器对象获取请求,响应对象
     * @param chain   过滤器链
     * @return
     */
    @Override
    public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {
        ServerHttpRequest request = exchange.getRequest();
        ServerHttpResponse response = exchange.getResponse();
        //1.对于静态资源 js css img 直接放行
        //1.1 获取请求路径地址  getURI()  www.list.gmall.com/ab/cd   getURI().getPath() /ab/cd
        String urlPath = request.getURI().getPath();
        //1.2 采用地址匹配器进行判断
        if (antPathMatcher.match("**/js/**",urlPath) || antPathMatcher.match("**/img/**", urlPath) ||
                antPathMatcher.match("**/css/**", urlPath)){
            return  chain.filter(exchange);
        }
        //2.对于请求地址中包含"inner"说明该接口用于服务间调用,无论登录与否,都禁止直接通过网关访问
        if (antPathMatcher.match("/**/inner/**", urlPath)){
            return  outError(response, ResultCodeEnum.ILLEGAL_REQUEST);
        }
        //3.尝试从Redis中获取用户信息
        String userId = this.getUserId(request);
        //尝试获取临时用户ID
        String userTempId = this.getUserTempId(request);
        if (StringUtils.isBlank(userId)){
            //3.1对于某些ajax请求包含"auth"只有登录后才可以访问,如果用户没登录响应401没有权限访问
            if (antPathMatcher.match("/**/auth/**", urlPath)){
                return outError(response, ResultCodeEnum.LOGIN_AUTH);
            }


        //3.2对于前端部分页面访问  例如 :  我的订单页面 我的购物车页面 等这些页面,只有登录后才可以访问,引导用户登录
        for (String url : authUrl) {
            if (antPathMatcher.match("/"+url,urlPath)){
                //设置响应http状态码
                response.setStatusCode(HttpStatus.SEE_OTHER);
                //设置重定向地址 浏览器会解析响应头地址 进行浏览器重定向
                response.getHeaders().set(HttpHeaders.LOCATION,"http://passport.gmall.com/login.html?originUrl="+request.getURI());
                return  response.setComplete();
            }
        }
    }
        //4.动态路由同时将获取到用户ID设置到请求头中,将用户ID透传到目标微服务中
        if (StringUtils.isNotBlank(userId)){
            request.mutate().header("userId",userId);
        }
        //降临时用户ID 透传到 目标微服务中
        if (StringUtils.isNotBlank(userTempId)){
            request.mutate().header("userTempId",userTempId);
        }
        return chain.filter(exchange);
    }

    /**
     * 尝试获取临时用户ID,只用于购物车模块
     * @param request
     * @return
     */
    private String getUserTempId(ServerHttpRequest request) {
        String userTempId = request.getHeaders().getFirst("userTempId");
        if (StringUtils.isBlank(userTempId)) {
            HttpCookie cookie = request.getCookies().getFirst("userTempId");
            if (cookie != null) {
                userTempId = cookie.getValue();
                return userTempId;
            }
        }
        return null;
    }

    @Override
    public int getOrder() {
        return 1;
    }

    public static void main(String[] args) {
        AntPathMatcher antPathMatcher=new AntPathMatcher();
        boolean match = antPathMatcher.match("/**/inner/**", "/api/product/inner/getSkuInfo/24");
        System.out.println(match);
    }
    /**
     * TODO 在网关模块使用Redis模板对象,使用默认的序列化器
     * 前端
     * 提交ajax请求,将token放在请求头token 中提交
     * 浏览器地址栏同步请求,将token放在cookie中提交 cookieName=token
     * 获取当前用户ID
     *
     * @return
     */
    private String getUserId(ServerHttpRequest request) {
        //1.尝试从请求头或者cookie中获取用户令牌
        String token = request.getHeaders().getFirst("token");
        if (StringUtils.isBlank(token)) {
            HttpCookie cookie = request.getCookies().getFirst("token");
            if (cookie != null) {
                token = cookie.getValue();
            }
        }
        if (StringUtils.isBlank(token)) {
            return null;
        }
        //2.从redis中获取用户信息
        String tokenKey = "user:" + token;
        JSONObject userJsonObject = (JSONObject) redisTemplate.opsForValue().get(tokenKey);
        if (userJsonObject != null) {
            return userJsonObject.get("id").toString();
        }
        return null;
    }
    /**
     * 用来给前端响应错误提示信息
     *
     * @param response
     * @param resultCodeEnum
     * @return
     */
    private Mono<Void> outError(ServerHttpResponse response, ResultCodeEnum resultCodeEnum) {
        //1.准备响应结果对象,转为JSON对象
        Result<Object> result = Result.build(null, resultCodeEnum);
        String resultString = JSON.toJSONString(result);

        //2.响应结果给客户端
        //2.1 设置http状态码
        response.setStatusCode(HttpStatus.UNAUTHORIZED);
        //2.2 通过响应头设置响应数据格式-json
        response.getHeaders().add("content-type", "application/json;charset=utf-8");
        DataBuffer wrap = response.bufferFactory().wrap(resultString.getBytes());
        //2.3 网关结束响应-不再路由转发
        //return response.setComplete();
        //2.4 网关将响应数据返回给客户端
        return response.writeWith(Mono.just(wrap));
    }
}
